package com.nf.health.app.homepage.activity;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.DashPathEffect;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.my.SearchDrugStoreActivity;
import com.nf.health.app.adapter.NewCheckResultAdapter;
import com.nf.health.app.customview.CustomShareBoard;
import com.nf.health.app.customview.MyListView;
import com.nf.health.app.models.Result;
import com.nf.health.app.utils.SharePlatform;
import com.nf.health.app.utils.ViewUtil;
import com.nf.health.app.widget.MyPhysiqueBarChatXAxisFormatter;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class NewCheckResultActivity extends BaseActivity {

    private final UMSocialService mController = UMServiceFactory
            .getUMSocialService(Constants.DESCRIPTOR);

    @Bind(R.id.tv_check_result)
    TextView mTvCheckResult;
    @Bind(R.id.bar_chart)
    BarChart mChart;
    @Bind(R.id.tv_note)
    TextView mTvNote;
    @Bind(R.id.lv_result)
    MyListView mLvResult;
    @Bind(R.id.btn_re_check)
    Button mBtnReCheck;
    @Bind(R.id.titlebar_title_tv)
    TextView mTitlebarTitleTv;
    @Bind(R.id.titlebar_right_view)
    ImageView mTitlebarRightView;
    private Result mResultBean;
    private String httpUrl = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_new_check_result);
        ButterKnife.bind(this);
        initView();
        initListener();

    }

    private void initView() {
        mChart.setNoDataText("没有数据");
        mResultBean = (Result) getIntent().getSerializableExtra(Constants.BEAN_KEY);
        if(mResultBean == null){
            return;
        }
        httpUrl = mResultBean.getUrl();
        initBarChat();
        ViewUtil.setImageResoure(this, R.id.titlebar_right_view, R.drawable.iv_go_share);
        mTitlebarTitleTv.setText("检测结果详情");
        mTvCheckResult.setText("您的体质检测结果是:" + (TextUtils.isEmpty(mResultBean.getResult())?"":mResultBean.getResult()));
        //由于某个控件获取了焦点，ScrollView会自己向下滑动一段距离，所以让靠上的控件先获取焦点，这样就不会向下滑动了
        mTvCheckResult.setFocusable(true);
        mTvCheckResult.setFocusableInTouchMode(true);
        mTvCheckResult.requestFocus();

        NewCheckResultAdapter adapter = new NewCheckResultAdapter(this, mResultBean.getList());
        mLvResult.setAdapter(adapter);

        //给TextView中的某段文字设置点击事件
        mTvNote.setText(getClickableSpan());
        mTvNote.setMovementMethod(LinkMovementMethod.getInstance());//必须设置否则无效
    }

    private void initListener() {
        mBtnReCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTitlebarRightView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomShareBoard shareBoard = new CustomShareBoard(NewCheckResultActivity.this);
                shareBoard.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
                //再设置模式，和Activity的一样，覆盖，调整大小。
                shareBoard.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                shareBoard.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
                shareBoard.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);


                // 配置需要分享的相关平台
                configPlatforms();
                // 设置分享的内容
                setShareContent();
            }
        });
    }

    /**
     * 初始化图表
     */
    private void initBarChat() {
        mChart.setDrawBarShadow(false);
        mChart.setDrawValueAboveBar(true);
        mChart.getDescription().setEnabled(false);
        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        mChart.setMaxVisibleValueCount(60);
        // scaling can now only be done on x- and y-axis separately
        mChart.setPinchZoom(false);
        mChart.setDrawGridBackground(false);
        //点击Item上方的提示，设置为不显示
        mChart.setDrawMarkers(false);
        //点击Item是否高亮显示
        //mChart.setHighlightFullBarEnabled(false);
        mChart.setHighlightPerTapEnabled(false);
        mChart.setHighlightPerDragEnabled(false);
        //设置是否缩放
        mChart.setScaleEnabled(false);
        if(mResultBean.getEval() == null){
            return;
        }

        IAxisValueFormatter xAxisFormatter = new MyPhysiqueBarChatXAxisFormatter(mResultBean.getEval().getEvalArray());

        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawAxisLine(false);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f); // only intervals of 1 day
        xAxis.setLabelCount(9);  //标签数量  是每个柱形图下面的文字描述
        xAxis.setValueFormatter(xAxisFormatter);

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setAxisMaximum(100f);
        leftAxis.setSpaceTop(15f);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        leftAxis.setDrawAxisLine(false);
        leftAxis.setDrawGridLines(true);
        leftAxis.setDrawZeroLine(false);
        leftAxis.setGridDashedLine(new DashPathEffect(new float[]{2, 2, 2, 2}, 0));
        //不绘制右侧的Y轴
        YAxis rightAxis = mChart.getAxisRight();
        rightAxis.setEnabled(false);

        Legend l = mChart.getLegend();
        //是否使用Item的描述
        l.setEnabled(false);

        setData(mResultBean.getEval().getEvalArray());
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
    }


    private SpannableString getClickableSpan() {
        View.OnClickListener l = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(NewCheckResultActivity.this, SearchDrugStoreActivity.class));
            }
        };

        SpannableString spanableInfo = new SpannableString(
                "注：本次监测结果仅供参考，如需详细了解请前往附近医院进行了解");
        int start = 22;
        int end = 26;
        spanableInfo.setSpan(new Clickable(l), start, end,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spanableInfo;
    }

    /**
     * 内部类，用于截获点击富文本后的事件
     */
    class Clickable extends ClickableSpan implements View.OnClickListener {
        private final View.OnClickListener mListener;

        public Clickable(View.OnClickListener mListener) {
            this.mListener = mListener;
        }

        @Override
        public void onClick(View v) {
            mListener.onClick(v);
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(getResources().getColor(R.color.theme_color));
            ds.setUnderlineText(true);    //去除超链接的下划线
        }
    }


    /**
     * 给图表设置数据
     */
    private void setData(List<Result.EvalBean.EvalArrayBean> array) {

        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();

        for (int i = 0; i < array.size(); i++) {

            yVals1.add(new BarEntry(i + 1, Float.parseFloat(array.get(i).getScore())));
        }

        BarDataSet set1;

        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        } else {
            set1 = new BarDataSet(yVals1, "");


            //set1.setColors(ColorTemplate.MATERIAL_COLORS);
            set1.setColors(ColorTemplate.MY_BLUE_COLORS);

            ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            data.setBarWidth(0.7f);

            mChart.setData(data);
        }
        //不显示value
        for (IDataSet set : mChart.getData().getDataSets())
            set.setDrawValues(!set.isDrawValuesEnabled());
    }

    private void setShareContent() {

        // 配置SSO
        mController.getConfig().setSsoHandler(new SinaSsoHandler());
        UMImage umImage;
        umImage = new UMImage(this, BitmapFactory.decodeResource(getResources(),R.mipmap.ic_logo));
        String targetUrl = httpUrl;
        String content = "我的体质是" + mResultBean.getResult() + "，快来测一测你属于哪种体质。";
        String title = "中医九种体质判定";

        // 微信分享必须设置targetURL，需要为http链接格式
        // 微信朋友圈只能显示title，并且过长会被微信截取部分内容
        WeiXinShareContent weixinContent = new WeiXinShareContent();
        weixinContent.setShareContent(content);
        weixinContent.setTitle(title);
        weixinContent.setTargetUrl(targetUrl);
        weixinContent.setShareMedia(umImage);
        mController.setShareMedia(weixinContent);

        // 设置朋友圈分享的内容
        CircleShareContent circleMedia = new CircleShareContent();
        circleMedia.setShareContent(content);
        circleMedia.setTitle(title);
        circleMedia.setShareMedia(umImage);
        circleMedia.setTargetUrl(targetUrl);
        mController.setShareMedia(circleMedia);

        //QQ content 最多两行，超过的话，导致显示不全，也没有显示成...， 就是直接少了后面的一块内容，所以，最多两行
        QQShareContent qqShareContent = new QQShareContent();
        qqShareContent.setShareContent(content);
        qqShareContent.setTitle(title);
        qqShareContent.setShareMedia(umImage);
        qqShareContent.setTargetUrl(targetUrl);
        mController.setShareMedia(qqShareContent);
        // 设置QQ空间分享内容
        QZoneShareContent qzone = new QZoneShareContent();
        qzone.setTargetUrl(targetUrl);
        qzone.setShareContent(content);
        qzone.setTitle(title);
        qzone.setShareMedia(umImage);
        mController.setShareMedia(qzone);
        //新浪微博、腾讯微博及豆瓣的跳转链接只能设置在分享文字之中，以http形式传递即可，人人网可以单独设置跳转链接，方法为：
        SinaShareContent sinaContent = new SinaShareContent();
        sinaContent.setShareContent(content);
        sinaContent.setTitle(title);
        sinaContent.setShareImage(umImage);
        mController.setShareMedia(sinaContent);
    }


    private void configPlatforms() {
        // 添加新浪SSO授权
        mController.getConfig().setSsoHandler(new SinaSsoHandler());
        SharePlatform.addQQ_QZonePlatform(this);
        SharePlatform.addWXPlatform(this);
    }
}
